<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :custom-class="'panna-dialog_medium'"
      :append-to-body="true"
      title="新增被采样单位"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="formData"
        label-width="130px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          label="上级"
          :label-width="formLabelWidth"
          prop="parentLevel"
          style="width: 100%"
          :error="errorMsg.parentLevel"
        >
          <BaseTreeSelect
            ref="TreeSelect"
            v-model="formData.parentLevel"
            node-key="id"
            :tree-data.sync="samplingUnitTreeData"
            :display-superior-state.sync="displaySuperiorState"
            :superior-name="superiorName"
          />
        </el-form-item>

        <el-form-item
          label="单位名称"
          :label-width="formLabelWidth"
          prop="unitName"
          style="width: 100%"
          :error="errorMsg.unitName"
        >
          <el-input v-model="formData.unitName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="编码"
          :label-width="formLabelWidth"
          prop="code"
          style="width: 100%"
          :error="errorMsg.code"
        >
          <el-input v-model="formData.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="点位类型"
          :label-width="formLabelWidth"
          prop="pointType"
          style="width: 100%"
          :error="errorMsg.pointType"
        >
          <el-input v-model="formData.pointType" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="备注"
          :label-width="formLabelWidth"
          prop="remark"
          style="width: 100%"
          :error="errorMsg.remark"
        >
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            maxlength="50"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="采样地点" :label-width="formLabelWidth" style="width: 100%">
              <el-row
                v-for="(item, index) in formData.samplingPositions"
                :key="index"
                style="margin-bottom: 5px"
              >
                <el-col>
                  <el-input
                    v-model="formData.samplingPositions[index].position"
                    autocomplete="off"
                    style="width: 90%; float: left"
                  ></el-input>
                  <div class="addCustomer" style="margin-right: 32px" @click="addPosition">+</div>
                  <div
                    v-if="index > 0"
                    class="addCustomer"
                    style="background-color: red"
                    @click="removePosition(index)"
                  >-</div>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button
          :disabled="!submitLoad"
          type="primary"
          @click="onSubmit('formData')"
          >保 存</el-button
        >
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  create,
  update,
  getSamplingUnitTree,
  get,
} from "../../../api/Sampling/SamplingUnit.js";
import { formatData } from "../../../utils/index";
import _ from "lodash";
export default {
  name: "SamplingUnitEdit",
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: "",
    },
    nodeId: {
      type: String,
      default: "",
    },
    unitName: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      submitLoad: true,
      superiorName: "",
      displaySuperiorState: true,
      loading: false,
      formLabelWidth: "100px",
      formData: {
        id: 0,
        unitName: "",
        rankOrder: 0,
        parentLevel: "",
        creatorId: 0,
        samplingPositions: [{ samplingUnitId: 0, position: "", creatorId: 0 }],
        deleteSamplingPositions: [],
      },
      samplingUnitTreeData: [],

      formDataRules: {
        parentLevel: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        unitName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        rankOrder: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        creatorId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
      },
      initErrorMsg: {
        unitName: "",
        rankOrder: "",
        parentLevel: "",
        creatorId: "",
      },
      errorMsg: {
        unitName: "",
        rankOrder: "",
        parentLevel: "",
        creatorId: "",
      },
    };
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      await this.getOption();
      this.formData.parentLevel = this.nodeId;
      this.superiorName = this.unitName;

      if (this.editId !== "" && this.editId !== null) {
        get({ id: this.editId }).then((res) => {
          this.formData = res.data;
          this.superiorName = res.data.superiorName;
          this.formData.parentLevel = res.data.parentLevel;
        });
      }
    },
    getOption() {
      return new Promise((resolve) => {
        getSamplingUnitTree().then((res) => {
          this.samplingUnitTreeData = formatData(res.data, {
            value: "id",
            label: "unitName",
          });
          resolve();
        });
      });
    },
    addPosition() {
      this.formData.samplingPositions.push({
        samplingUnitId: 0,
        position: "",
        creatorId: 0,
      });
    },
    removePosition(index) {
      if (
        this.formData.deleteSamplingPositions === null ||
        this.formData.deleteSamplingPositions.length === 0
      ) {
        this.formData.deleteSamplingPositions = [];
      }
      this.formData.deleteSamplingPositions.push(
        this.formData.samplingPositions[index]
      );
      this.formData.samplingPositions.splice(index, 1);
    },

    closeDialog() {
      this.$parent.getTreeList();
      this.handleClose();
    },
    handleClose() {
      this.$emit("update:editId", "");
      this.$emit("update:dialogFormVisible", false);
    },

    onSubmit: _.throttle(function() {
      if (this.submitLoad) {
        this.submitLoad = false;
        this.$refs.formData.validate((valid) => {
          if (valid) {
            this.loading = true;
            this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
            if (this.formData.id <= 0) {
              create(this.formData)
                .then((res) => {
                  if (res.code === 200) {
                    this.closeDialog();
                    this.submitLoad = true;
                  } else {
                    this.showValidateMsgCheck(res);
                    this.submitLoad = true;
                  }
                  this.submitLoad = true;

                  this.loading = false;
                })
                .catch(() => {
                  this.submitLoad = true;

                  this.loading = false;
                });
            } else {
              update(this.formData)
                .then((res) => {
                  if (res.code === 200) {
                    this.closeDialog();
                    this.submitLoad = true;
                  } else {
                    this.showValidateMsgCheck(res);
                    this.submitLoad = true;
                  }
                  this.loading = false;
                  this.submitLoad = true;
                })
                .catch(() => {
                  this.loading = false;
                  this.submitLoad = true;
                });
            }
          } else {
            this.submitLoad = true;
            return false;
          }
        });
      }
    }, 2000),
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("unitName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("rankOrder", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("parentLevel", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creatorId", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.addCustomer {
  width: 30px;
  color: white;
  font-size: 20px;
  height: 32px;
  text-align: center;
  border-radius: 5px;
  border: 1px silver;
  background-color: #4787ff;
  position: absolute;
  top: 0px;
  right: 0px;
}
</style>
